<?php

namespace app\controllers;

use Yii;
use app\models\SamplePosition;
use app\models\SamplePositionAlter;
use app\models\SamplePositionElse;
use app\models\SampleAlter;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

// test again again.... i think this is the last time!!!!!
/**
 * XnaController implements the CRUD actions for SamplePositionElse model.
 */
class XnaController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all SamplePositionElse models.
     * @return mixed
     */
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => SamplePositionElse::find(),
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single SamplePositionElse model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $modelFrom = SamplePosition::findOne($id);
        $model = SamplePositionElse::find()->where(['from_id' => $modelFrom->xna_id])->with("alter")->orderBy(["crt_time" => "SORT_DESC"])->all();

        return $this->render('/sample/xna', [
            'view' => 'view',
            'info' => $modelFrom,
            'model' => $model,
        ]);
    }

    /**
     * Creates a new SamplePositionElse model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreateM()
    {
        $model = new SamplePositionElse();

        $type = Yii::$app->request->get('type');
        $model->from_id = Yii::$app->request->get('from', '');
        $model->xna_id = $model->from_id."-M";

        if ($model->load(Yii::$app->request->post())) {
            $model->xna_volumn_left = $model->xna_volumn;
            $model = $this->addCrtInfo($model);

            return $this->saveToDB([$model]);
        } else {

            return $this->render('/sample/xna', [
                'view' => 'xna',
                'model' => $model,
            ]);
        }
    }

    public function actionCreateDna()
    {
        $from_id = Yii::$app->request->get('from', '');
        $alter = new SampleAlter();

        if (Yii::$app->request->isPost) {
            $model = $this->findSample($from_id.'-'.Yii::$app->request->post('order'));
            $modelM = $this->findSample($from_id.'-M');

            if ($alter->load(Yii::$app->request->post())) {

                $model->load(Yii::$app->request->post());
                $this->dealData($model, $alter, $from_id);
                $modelAlter = $this->dealPositionAlter(Yii::$app->request->post(), $model);

                $msg = $this->checkVolumnAndisNew($modelM, $model, $alter);
                if ($msg != 'success') return $msg;

                return $this->saveToDB([$model, $modelM, $alter, $modelAlter]);
            }
        } else {
            $from = SamplePositionElse::findOne(['xna_id' => $from_id."-M"]);
            $model = new SamplePositionElse();
            $model->from_id = $from_id;
            $model->xna_density = $from->xna_density;
            $alter->origin_density = $from->xna_density;

            return $this->render('/sample/xna', [
                'view' => 'xna',
                'model' => $model,
                'alter' => $alter,
                'type' => 1,
            ]);
        }
    }

    public function actionCreateRna()
    {
        $from_id = Yii::$app->request->get('from', '');
        $alter = new SampleAlter();

        if (Yii::$app->request->isPost) {
            $model = $this->findSample($from_id.'-M');

            if ($alter->load(Yii::$app->request->post())) {

                $model->load(Yii::$app->request->post());
                $this->dealData($model, $alter, $from_id);
                $modelAlter = $this->dealPositionAlter(Yii::$app->request->post(), $model);

                $msg = $this->checkVolumnAndisNew(null, $model, $alter);
                if ($msg != 'success') return $msg;

                return $this->saveToDB([$model, $alter, $modelAlter]);
            }
        } else {
            $model = SamplePositionElse::findOne(['xna_id' => $from_id."-M"]);
            $alter->origin_density = $model->xna_density;

            return $this->render('/sample/xna', [
                'view' => 'xna',
                'model' => $model,
                'alter' => $alter,
                'type' => 2,
            ]);
        }
    }

    public function actionDetail()
    {
        $from_id = Yii::$app->request->post('from_id');
        $result = ['data', 'alter'];

        if (preg_match('/-[A-D]/', $from_id)) {
            $dataProvider = SamplePositionElse::find()->where(['xna_id' => $from_id."-M"])->with('alter')->one();

            $result['data'][] = $dataProvider->attributes;
            foreach ($dataProvider->alter as $alter) {
                $result['alter'][] = $alter->attributes;
            }

        } else {
            $dataProvider = SamplePositionElse::find()->where(['and', ['from_id' => $from_id], ['not like', 'xna_id', '-M']])->with('alter')->all();

            foreach ($dataProvider as $data) {
                $result['data'][] = $data->attributes;
                foreach ($data->alter as $alter) {
                    $result['alter'][] = $alter->attributes;
                }
            }
        }

        return json_encode($result);
    }

    public function actionFindExist()
    {
        $xna_id = Yii::$app->request->post('xna_id');
        $result = $this->findSample($xna_id);

        return json_encode($result->attributes);
    }

    /**
     * Updates an existing SamplePositionElse model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $type = Yii::$app->request->get("type");
        $from = Yii::$app->request->get("from", '');
        $model = ($type == 'alter') ? $this->findAlter($id) : $this->findModel($id);
        $type = ($type == 'alter') ? 'alter' : 'model';

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            if ($type != 'alter') {

                $modelAlter = $this->dealPositionAlter(Yii::$app->request->post(), $model);
                $modelAlter->sample_id = $model->pk_id;
                if (!$modelAlter->save()) {
                    return 'fail';
                }
            }
            return 'success';
        } else {

            return $this->render('/sample/xna', [
                'view' => 'update',
                'type' => (preg_match('/-[A-D]-/', $model->xna_id)) ? 2 : 1,
                'info' => $from,//sorry.....
                $type => $model,
            ]);
        }
    }

    /**
     * Deletes an existing SamplePositionElse model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the SamplePositionElse model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return SamplePositionElse the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = SamplePositionElse::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    protected function findSample($xna_id)
    {
        if (($model = SamplePositionElse::findOne(['xna_id' =>  $xna_id])) !== null) {
            return $model;
        } else {
            $model = new SamplePositionElse();
            $model->xna_id = $xna_id;
            return $model;
        }
    }

    protected function findAlter($id)
    {
        if (($model = SampleAlter::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    protected function addCrtInfo($model)
    {
        $model->crt_name = Yii::$app->user->identity->username;
        $model->crt_time = date("Y-m-d H:i:s");
        return $model;
    }

    protected function dealData($model, $alter, $from_id)
    {
        if ($model->isNewRecord()) {
            $model->from_id = $from_id;
            $model->xna_volumn_left = $model->xna_volumn;
            $model = $this->addCrtInfo($model);
        }

        $alter = $this->addCrtInfo($alter);
    }

    protected function dealPositionAlter($post, $model)
    {
        $modelAlter = new SamplePositionAlter();
        $modelAlter->load(Yii::$app->request->post(), "SamplePositionElse");
        $modelAlter->xna_type = (preg_match('/-[A-D]-/', $model->from_id)) ? 'rna' : 'dna';
        $modelAlter = $this->addCrtInfo($modelAlter);

        return $modelAlter;
    }

    protected function checkVolumnAndisNew($modelM, $model, $alter)
    {
        if ($model->isNewRecord()) {
            $msg = $modelM->isEnough($model->xna_volumn_left);
            if ($msg != 'success') return $msg;
        }

        $msg = $model->isEnough($alter->use_num);
        if ($msg != 'success') return $msg;

        return 'success';
    }

    protected function saveToDB($models)
    {
        foreach ($models as $key => $model) {
            if (get_class($model) == 'app\models\SampleAlter') {
                $model->from_id = $models[0]->pk_id;
            }

            if (get_class($model) == 'app\models\SamplePositionAlter') {
                if ($model->case == '') continue;

                $model->sample_id = $models[0]->pk_id;
            }

            if (!$model->save()) {
                echo var_dump($model->errors);
                return '保存失败，';
            }
        }

        return 'success';
    }
}
